package com.ruoyi.capsule.controller;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController()
@RequestMapping("/bole")
public class BoleLoginController {
    @Autowired
    private ISysUserService iuserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private RedisCache redisCache;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        System.out.println(loginBody.toString());
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest())

        ajax.put(Constants.TOKEN, token);
        ajax.put("user", iuserService.selectUserByUserName(loginBody.getUsername()));
        return ajax;
    }


    //修改密码
    @PostMapping("/resetPassword")
    public AjaxResult resetPassword(String email,Integer code,String password,String userName)
    {
        //先检验该用户是否存在
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setEmail(email);

        sysUser = iuserService.selectUserByUserName(userName);;
        if (sysUser==null){
            return AjaxResult.error("请检查用户名或邮箱");
        }
//        System.out.println(redisCache.getCacheObject("Find:findPasswordCode:"+email);
        Integer cachedCode = (Integer) redisCache.getCacheObject("Find:findPasswordCode:" + email);
        System.out.println(cachedCode);

        if (cachedCode != null && code.equals(cachedCode)) {
            SysUser sysUserNew = new SysUser();
            sysUserNew.setUserId(sysUser.getUserId());
            sysUserNew.setPassword(SecurityUtils.encryptPassword(password));
            iuserService.updateUser(sysUserNew);
            return AjaxResult.success("修改成功");
        }else{
            return AjaxResult.error("验证码错误");
        }
    }


}
